package com.yangtzeu.jwc.activity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yangtzeu.jwc.business.MCallBack;
import com.yangtzeu.jwc.business.NoteBusiness;
import com.yangtzeu.jwc.domain.MyJson;
import com.yangtzeu.jwc.domain.Note;
import com.zhangdi.jwc.R;
import com.zjsx.lib.utils.DataUtil;
import com.zjsx.lib.utils.InputUtil;
import com.zjsx.lib.utils.L;
import com.zjsx.lib.utils.StrUtil;
import com.zjsx.lib.utils.T;
import com.zjsx.lib.utils.TimeUtils;

public class NoteActivity extends BaseActivity implements OnItemClickListener, OnRefreshListener {
    SwipeRefreshLayout noteListRefreshLayout;
    RelativeLayout tip_pull_refresh;
    ListView noteList;
    View loadMoreView;
    TextView refreshText;
    ProgressBar refreshProgress;
    List<Note> notes = new ArrayList<Note>();
    List<Note> topNotes = new ArrayList<Note>();
    int curPage = 1;
    int curstart = 0;
    int totalPage = 0;
    NoteBusiness nb;
    LinearLayout writeNote;
    EditText etNote;
    TextView tvCommitNote;
    TextView tvNoteEditInfo;
    int noteDeep = 0;
    int noteReplyId = 0;
    boolean isLoading = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
    }

    @Override
    public void setView() {
	// TODO Auto-generated method stub
	super.setView();
	setContentView(R.layout.activity_note);
    }

    @Override
    public void initData() {
	// TODO Auto-generated method stub
	super.initData();
	nb = new NoteBusiness(this);
    }

    @Override
    public void initActionBar() {
	// TODO Auto-generated method stub
	super.initActionBar();
	setSimpleActionBar("返回", "", "小小留言板", "我要留言");
    }

    @Override
    public void initView() {
	// TODO Auto-generated method stub
	super.initView();
	tip_pull_refresh = (RelativeLayout) findViewById(R.id.refresh_tip);
	noteListRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.notelist_refresh_layout);
	noteListRefreshLayout.setOnRefreshListener(this);
	noteListRefreshLayout.setColorSchemeResources(R.color.main_blue_color, R.color.red, R.color.yellow, R.color.teal);
	noteList = (ListView) findViewById(R.id.noteList);
	loadMoreView = getLayoutInflater().inflate(R.layout.load_more_footer, null);
	refreshProgress = (ProgressBar) loadMoreView.findViewById(R.id.refresh_progress);
	refreshText = (TextView) loadMoreView.findViewById(R.id.refresh_text);
	noteList.addFooterView(loadMoreView);
	noteList.setOnItemClickListener(this);
	writeNote = (LinearLayout) findViewById(R.id.write_note);
	etNote = (EditText) findViewById(R.id.et_note);
	tvCommitNote = (TextView) findViewById(R.id.commit_note);
	tvNoteEditInfo = (TextView) findViewById(R.id.note_edit_info);
	noteList.setAdapter(adapter);
	noteList(curPage);
    }

    @Override
    public void initListener() {
	// TODO Auto-generated method stub
	super.initListener();
	tvCommitNote.setOnClickListener(this);
    }

    @Override
    public void initAdapter() {
	// TODO Auto-generated method stub
	super.initAdapter();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
	if (keyCode == KeyEvent.KEYCODE_BACK) {
	    if (writeNote.getVisibility() == View.VISIBLE) {
		handler.sendEmptyMessage(HIDE_NOTE);
		return true;
	    }
	}
	return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
	// TODO Auto-generated method stub
	super.onClick(v);
	switch (v.getId()) {
	case R.id.tv_title_right:
	    
	    if (writeNote.getVisibility() == View.GONE) {
		noteDeep = 0;
		noteReplyId = 0;
		etNote.setText("");
		handler.sendEmptyMessage(SHOW_NOTE);
		tvCommitNote.setText("留言");
	    } else {
		handler.sendEmptyMessage(HIDE_NOTE);
	    }
	    break;
	case R.id.commit_note:
	    commitNote();
	    break;
	case R.id.note_up:
	    upDown((Note) (v.getTag()), 1);
	    break;
	case R.id.note_down:
	    upDown((Note) (v.getTag()), -1);
	    break;
	case R.id.write_note_outer:
	    handler.sendEmptyMessage(HIDE_NOTE);
	    break;
	case R.id.note_reply:
	    etNote.setHint("请填写回复内容");
	    Note n = (Note) (v.getTag());
	    if (n.replyid == 0) {// 回复第一级
		if (n.replys != null && n.replys.length > 19) {
		    T.showShort(this, "该楼层回复过多,不能再回复！");
		    return;
		}
		noteDeep = 1;
		noteReplyId = n.id;
		etNote.setText("");
		handler.sendEmptyMessage(SHOW_NOTE);
		tvCommitNote.setText("回复");
		tvNoteEditInfo.setText("回复："+n.username);
	    } else { // 回复第二级
		for (Note note : notes) {
		    if (note.id == n.replyid) {
			if (note.replys != null && note.replys.length > 19) {
			    T.showShort(this, "该楼层回复过多,不能再回复！");
			    return;
			}
		    }
		}
		noteDeep = 1;
		noteReplyId = n.replyid;
		String text = "回复#" + n.floor + ":";
		etNote.setText(text);
		etNote.setSelection(text.length());
		handler.sendEmptyMessage(SHOW_NOTE);
		tvCommitNote.setText("回复");
		tvNoteEditInfo.setText("回复："+n.username);
	    }
	    break;
	default:
	    break;
	}
    }

    public final int SHOW_NOTE = 1;
    public final int HIDE_NOTE = 2;
    public final int CLEAR_NOTE = 3;
    public final int SHOW_FOOTER = 4;
    public final int HIDE_FOOTER = 5;
    public final int LOADING = 6;
    public final int LOADING_COMPLITE = 7;

    @Override
    public void handleMsg(Message msg) {
	switch (msg.what) {
	case SHOW_NOTE:
	    writeNote.setVisibility(View.VISIBLE);
	    etNote.requestFocus();
	    InputUtil.ShowKeyboard(etNote);
	    break;
	case HIDE_NOTE:
	    writeNote.setVisibility(View.GONE);
	    InputUtil.KeyBoard(etNote, "close");
	    break;
	case CLEAR_NOTE:
	    etNote.setText("");
	    writeNote.setVisibility(View.GONE);
	    InputUtil.KeyBoard(etNote, "close");
	    break;
	case SHOW_FOOTER:
	    refreshProgress.setVisibility(View.GONE);
	    refreshText.setVisibility(View.VISIBLE);
	    break;
	case HIDE_FOOTER:
	    refreshProgress.setVisibility(View.GONE);
	    refreshText.setVisibility(View.GONE);
	    break;
	case LOADING:
	    refreshProgress.setVisibility(View.VISIBLE);
	    refreshText.setVisibility(View.GONE);
	    break;
	case LOADING_COMPLITE:
	    refreshProgress.setVisibility(View.GONE);
	    refreshText.setVisibility(View.VISIBLE);
	    noteListRefreshLayout.setRefreshing(false);
	    break;
	default:
	    break;
	}
    }

    private String checkNoteInput() {
	String content = etNote.getText().toString();
	if (StrUtil.isEmpty(content)) {
	    content = null;
	    T.showShort(this, "请填写留言内容");
	} else {
	    if (StrUtil.strLength(content) < 10) {
		content = null;
		T.showShort(this, "少于6个字的留言是不是太少了？");
	    } else if (StrUtil.strLength(content) > 500) {
		T.showShort(this, "多余于500（当前:" + StrUtil.strLength(content) + "）个字的留言是不是有点长了？");
		content = null;
	    }
	}
	return content;
    }

    private void upDown(final Note note, final int upDown) {
	nb.upDown(note, upDown, new MCallBack() {
	    @Override
	    public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
		T.showLong(NoteActivity.this, failuremsg);
	    }

	    @Override
	    public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, MyJson mj) {
		// T.showShort(NoteActivity.this, (upDown == 1) ? "点赞成功^_^" :
		// "踩成功-_-");
		Note tNote = DataUtil.dataToObj(mj.data, Note.class);
		if (tNote.deep == 0) {
		    for (Note n : notes) {
			if (n.id == tNote.id) {
			    n.up = tNote.up;
			    n.down = tNote.down;
			    n.upordown = tNote.upordown;
			}
		    }
		} else {
		    for (Note n : notes) {
			if (n.id == tNote.replyid) {// 找到父回复
			    for (Note sn : n.replys) {
				if (sn.id == tNote.id) {
				    sn.up = tNote.up;
				    sn.down = tNote.down;
				    sn.upordown = tNote.upordown;
				}
			    }
			}
		    }
		}
		adapter.notifyDataSetChanged();
	    }

	});
    }

    private void commitNote() {
	tvCommitNote.setEnabled(false);
	String content = checkNoteInput();
	if (content == null)
	    return;
	Note note = new Note();
	note.content = content;
	note.number = MainActivity.student.getSno();
	note.username = MainActivity.student.getSclass() + " " + MainActivity.student.getSname();
	note.deep = noteDeep;
	note.replyid = noteReplyId;
	nb.note(note, new MCallBack() {
	    @Override
	    public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
		T.showLong(NoteActivity.this, failuremsg);
		tvCommitNote.setEnabled(true);
	    }

	    @Override
	    public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, MyJson mj) {
		// TODO Auto-generated method stub
		super.onSuccess(responseBody, successMsg, isNoticeDialog, mj);
		tvCommitNote.setEnabled(true);
		T.showShort(NoteActivity.this, "留言成功");
		Note mNote = DataUtil.dataToObj(mj.data, Note.class);
		if (mNote.deep == 0) {
		    if (notes.size() > 0) {
			mNote.floor = notes.get(0).floor + 1;
		    } else {
			mNote.floor = 1;
		    }
		    topNotes.add(0, mNote);
		    notes.add(0, mNote);
		    adapter.notifyDataSetChanged();
		    handler.sendEmptyMessage(CLEAR_NOTE);
		} else {
		    for (Note n : topNotes) {
			if (n.id == mNote.replyid) {
			    mNote.parent = n;
			    int len = n.replys == null ? 0 : n.replys.length;
			    Note[] tempNotes = new Note[len + 1];
			    for (int i = 0; i < len; i++) {
				tempNotes[i] = n.replys[i];
			    }
			    if (len > 0) {
				mNote.floor = n.replys[len - 1].floor + 1;
			    } else {
				mNote.floor = 1;
			    }
			    tempNotes[len] = mNote;
			    n.replys = tempNotes;
			}
		    }
		    refreshList();
		    handler.sendEmptyMessage(CLEAR_NOTE);
		}
	    }

	});
    }

    public void refreshList() {
	notes.clear();
	for (Note note : topNotes) {
	    notes.add(note);
	    if (note.replys != null && note.replys.length > 0) {
		for (Note n : note.replys) {
		    notes.add(n);
		}
	    }
	}
	adapter.notifyDataSetChanged();
    }

    private void noteList(int page) {
	isLoading = true;
	nb.list(page, curstart, new MCallBack() {

	    @Override
	    public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
		// TODO Auto-generated method stub
		super.onFailure(responseBody, failuremsg, isNoticeDialog);
		T.showShort(NoteActivity.this, failuremsg);
		isLoading = false;
		handler.sendEmptyMessage(LOADING_COMPLITE);
		if (totalPage > 1 && curPage < totalPage) {
		    handler.sendEmptyMessage(SHOW_FOOTER);
		} else {
		    handler.sendEmptyMessage(HIDE_FOOTER);
		}
		if (notes.size() == 0) {
		    tip_pull_refresh.setVisibility(View.VISIBLE);
		}
	    }

	    @Override
	    public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, MyJson mj) {
		// TODO Auto-generated method stub
		tip_pull_refresh.setVisibility(View.GONE);
		isLoading = false;
		curPage = mj.page;
		totalPage = mj.totalPage;
		curstart = mj.curstart;
		Note[] noteArray = DataUtil.dataToObj(mj.data, Note[].class);
		L.d("noteList:" + Arrays.toString(noteArray));
		if (curPage == 1) {
		    notes.clear();
		    topNotes.clear();
		}
		for (Note note : noteArray) {
		    notes.add(note);
		    topNotes.add(note);
		    if (note.replys != null) {
			for (Note n : note.replys) {
			    n.parent = note;
			    notes.add(n);
			}
		    }
		}
		adapter.notifyDataSetChanged();
		handler.sendEmptyMessage(LOADING_COMPLITE);
		if (totalPage > 1 && curPage < totalPage) {
		    handler.sendEmptyMessage(SHOW_FOOTER);
		} else {
		    handler.sendEmptyMessage(HIDE_FOOTER);
		}
	    }

	});
    }

    BaseAdapter adapter = new BaseAdapter() {

	@Override
	public int getCount() {
	    // TODO Auto-generated method stub
	    return notes.size();
	}

	@Override
	public Note getItem(int arg0) {
	    // TODO Auto-generated method stub
	    return notes.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
	    // TODO Auto-generated method stub
	    return arg0;
	}

	@Override
	public View getView(int arg0, View arg1, ViewGroup arg2) {
	    // TODO Auto-generated method stub
	    Holder holder = null;
	    if (arg1 != null) {
		holder = (Holder) arg1.getTag();
	    } else {
		arg1 = getLayoutInflater().inflate(R.layout.note_list_item, null);
		holder = new Holder(arg1);
		arg1.setTag(holder);
	    }
	    Note note = getItem(arg0);
	    if (note.replyid == 0) {
		arg1.setPadding(10, 10, 10, 10);
		holder.noteInner.setPadding(0, 0, 0, 0);
		// arg1.setBackgroundColor(Color.rgb(255, 255, 255));
		holder.noteInner.setBackgroundColor(Color.rgb(255, 255, 255));
		holder.noteFloor.setText(note.floor + "楼");
		if (note.replys != null && note.replys.length > 0) {
		    holder.noteDivider.setVisibility(View.GONE);
		} else {
		    holder.noteDivider.setVisibility(View.VISIBLE);
		}
	    } else {
		holder.noteDivider.setVisibility(View.VISIBLE);
		if (note.parent.replys.length == 1) {
		    holder.noteInner.setBackgroundResource(R.drawable.box_full);
		} else if (note.floor == 1) {
		    holder.noteInner.setBackgroundResource(R.drawable.box_top);
		} else if (note.floor == note.parent.replys.length) {
		    holder.noteInner.setBackgroundResource(R.drawable.box_bottom);
		} else {
		    holder.noteInner.setBackgroundResource(R.drawable.box_middle);
		}
		// arg1.setPadding(20, 20, 20, 20);
		// arg1.setBackgroundColor(Color.rgb(255, 255, 200));
		holder.noteFloor.setText("#" + note.floor);
		arg1.setPadding(10, 0, 10, 0);
		holder.noteInner.setPadding(10, 10, 10, 10);
	    }
	    holder.noteName.setText(note.username);
	    holder.noteModel.setText(note.model);
	    holder.noteTime.setText(TimeUtils.getEasyTime(TimeUtils.getTimeFromMiniStr(note.time)));
	    holder.noteContent.setText(note.content);
	    if (note.upordown == 1) {
		holder.noteUp.setTextColor(getResources().getColor(R.color.indianred));
		holder.noteUp.setText("取消" + "(" + note.up + ")");
	    } else {
		holder.noteUp.setTextColor(Color.rgb(128, 128, 128));
		holder.noteUp.setText("赞" + "(" + note.up + ")");
	    }
	    holder.noteUp.setTag(note);
	    if (note.upordown == -1) {
		holder.noteDown.setTextColor(getResources().getColor(R.color.indianred));
		holder.noteDown.setText("取消" + "(" + note.down + ")");
	    } else {
		holder.noteDown.setTextColor(Color.rgb(128, 128, 128));
		holder.noteDown.setText("踩" + "(" + note.down + ")");
	    }
	    holder.noteDown.setTag(note);
	    holder.noteReply.setTag(note);
	    // setReplys(note, holder);
	    return arg1;
	}

	class Holder {
	    public TextView noteFloor;
	    public TextView noteName;
	    public TextView noteModel;
	    public TextView noteTime;
	    public TextView noteContent;
	    public TextView noteUp;
	    public TextView noteDown;
	    public TextView noteReply;
	    public LinearLayout note_replys;
	    public View noteDivider;
	    public View noteInner;

	    public Holder(View v) {
		noteFloor = (TextView) v.findViewById(R.id.note_floor);
		noteName = (TextView) v.findViewById(R.id.note_name);
		noteModel = (TextView) v.findViewById(R.id.note_model);
		noteTime = (TextView) v.findViewById(R.id.note_time);
		noteContent = (TextView) v.findViewById(R.id.note_content);
		noteUp = (TextView) v.findViewById(R.id.note_up);
		noteUp.setOnClickListener(NoteActivity.this);
		noteDown = (TextView) v.findViewById(R.id.note_down);
		noteDown.setOnClickListener(NoteActivity.this);
		noteReply = (TextView) v.findViewById(R.id.note_reply);
		noteReply.setOnClickListener(NoteActivity.this);
		note_replys = (LinearLayout) v.findViewById(R.id.note_replys);
		noteDivider = v.findViewById(R.id.note_divider);
		noteInner = v.findViewById(R.id.note_inner);
	    }
	}

	public void setReplys(Note note, Holder holder) {
	    if (note.replys == null) {
		holder.note_replys.setVisibility(View.GONE);
		return;
	    } else if (note.replys.length < 1) {
		holder.note_replys.setVisibility(View.GONE);
		return;
	    } else {
		holder.note_replys.setVisibility(View.VISIBLE);
	    }
	    holder.note_replys.removeAllViews();
	    for (Note n : note.replys) {
		View v = getLayoutInflater().inflate(R.layout.note_list_item_inner, null);
		ReplyHolder rh = new ReplyHolder(v);
		v.setTag(n);
		rh.noteFloor.setText("#" + n.floor);
		rh.noteName.setText(n.username);
		rh.noteModel.setText(n.model);
		rh.noteContent.setText(n.content);
		rh.noteTime.setText(TimeUtils.getEasyTime(TimeUtils.getTimeFromMiniStr(n.time)));
		rh.noteReply.setTag(n);
		if (n.upordown == 1) {
		    rh.noteUp.setTextColor(getResources().getColor(R.color.indianred));
		    rh.noteUp.setText("取消" + "(" + n.up + ")");
		} else {
		    rh.noteUp.setTextColor(Color.rgb(128, 128, 128));
		    rh.noteUp.setText("赞" + "(" + n.up + ")");
		}
		rh.noteUp.setTag(n);
		if (n.upordown == -1) {
		    rh.noteDown.setTextColor(getResources().getColor(R.color.indianred));
		    rh.noteDown.setText("取消" + "(" + n.down + ")");
		} else {
		    rh.noteDown.setTextColor(Color.rgb(128, 128, 128));
		    rh.noteDown.setText("踩" + "(" + n.down + ")");
		}
		rh.noteDown.setTag(n);
		holder.note_replys.addView(v);
	    }
	}

	class ReplyHolder {
	    public TextView noteFloor;
	    public TextView noteName;
	    public TextView noteModel;
	    public TextView noteTime;
	    public TextView noteContent;
	    public TextView noteUp;
	    public TextView noteDown;
	    public TextView noteReply;

	    public ReplyHolder(View v) {
		noteFloor = (TextView) v.findViewById(R.id.note_floor);
		noteName = (TextView) v.findViewById(R.id.note_name);
		noteModel = (TextView) v.findViewById(R.id.note_model);
		noteTime = (TextView) v.findViewById(R.id.note_time);
		noteContent = (TextView) v.findViewById(R.id.note_content);
		noteUp = (TextView) v.findViewById(R.id.note_up);
		noteUp.setOnClickListener(NoteActivity.this);
		noteDown = (TextView) v.findViewById(R.id.note_down);
		noteDown.setOnClickListener(NoteActivity.this);
		noteReply = (TextView) v.findViewById(R.id.note_reply);
		noteReply.setOnClickListener(NoteActivity.this);
	    }
	}
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
	// TODO Auto-generated method stub
	if (position == notes.size()) {
	    if (!isLoading) {
		handler.sendEmptyMessage(LOADING);
		noteList(curPage + 1);
	    }
	}
    }

    @Override
    public void onRefresh() {
	// TODO Auto-generated method stub
	curPage = 1;
	curstart = 0;
	noteList(curPage);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	// TODO Auto-generated method stub
	switch (item.getItemId()) {
	case R.id.new_note:
	    tvNoteEditInfo.setText("新的留言：");
	    etNote.setHint("请文明留言");
	    if (writeNote.getVisibility() == View.GONE) {
		noteDeep = 0;
		noteReplyId = 0;
		etNote.setText("");
		handler.sendEmptyMessage(SHOW_NOTE);
	    } else {
		handler.sendEmptyMessage(HIDE_NOTE);
	    }
	    break;

	default:
	    break;
	}
	return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	MenuInflater inflater = getMenuInflater();
	inflater.inflate(R.menu.note_menu, menu);
	return true;
    }

}
